package com.hongxun.design.fragments;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.hongxun.design.MyApp;
import com.hongxun.design.R;
import com.hongxun.design.activitys.BaseActivity;
import com.hongxun.design.activitys.HomePageActivity;
import com.hongxun.design.adapters.ProjectAdapter;
import com.hongxun.design.bean.ProjectItemBean;
import com.hongxun.design.bean.SearchProjectBean;
import com.hongxun.design.constant.Constant;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.ToastShow;
import com.hongxun.design.ui.MBaiduMap;
import com.hongxun.design.ui.dialogstyle.MyDialog;
import com.hongxun.design.ui.pickerview.lib.DensityUtil;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenu;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuCreator;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuItem;
import com.hongxun.design.ui.ui_listview.Swipemenulistview.SwipeMenuListView;
import com.hongxun.design.ui.ui_listview.refreshlist.SwipeRefreshListView;
import com.hongxun.design.utils.FragmentUtil;
import com.hongxun.design.utils.TimeUtil;
import com.hongxun.design.utils.fastjson.FastJsonUtil;
import com.hongxun.design.utils.fileutil.GetFileUtil;
import com.hongxun.design.utils.fileutil.SetFileUtil;
import com.hongxun.design.utils.httputil.HttpStringUtil;
import com.hongxun.design.utils.projectdatautil.DataFactory;
import com.qx.wz.util.internal.StringUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ProjectFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {
    SwipeRefreshListView listview_project;
    private Handler projectListHandler;
    private Handler searchAllProjectHandler;
    private Handler delExpMaterialHandler;
    List<ProjectItemBean> data;
    List<ProjectItemBean> Cachedata;
    ProjectAdapter adapter;

    public String type = MString.LIST;//切换标签
    int mposition = -1;//删除位置
    /**
     * 地图控件*
     */
    RelativeLayout map_item;
    LinearLayout statistics;
    TextView completed, ongoing;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View contactsLayout = inflater.inflate(R.layout.fragment_projectlayout,
                container, false);
        findView(contactsLayout);
        initialization();
        return contactsLayout;
    }

    /**
     * 改变展示样式*
     */
    public void changeStyle() {
        if (map_item == null) return;
        if (type.equals(MString.MAP)) {
            map_item.setVisibility(View.VISIBLE);
            listview_project.setVisibility(View.GONE);
        } else {
            map_item.setVisibility(View.GONE);
            listview_project.setVisibility(View.VISIBLE);
        }
    }

    /**
     * Map搜索*
     */
    String name = "";

    public void search_Map(String project_name) {
        if (MyApp.isOnLine) {
            if (!name.equals(project_name)) {
                this.name = project_name;
                MyApp.HTTP.SearchAllProject(searchAllProjectHandler, HttpStringUtil.SUCCESSED, project_name);
            } else if (name.length() == 0) {
                MyApp.HTTP.SearchAllProject(searchAllProjectHandler, HttpStringUtil.SUCCESSED, project_name);
            }
        } else {
            searchProjectBeanList = GetFileUtil.getMapProjectFile();
            if (!name.equals(project_name)) {
                this.name = project_name;
            }
            List<SearchProjectBean> searchProjectBeans = new ArrayList<>();
            for (SearchProjectBean s : searchProjectBeanList) {//过滤
                if (s.getProject_name().contains(project_name)) {
                    searchProjectBeans.add(s);
                }
            }
            searchProjectBeanList.clear();
            searchProjectBeanList.addAll(searchProjectBeans);

            searchAllProjectHandler.sendEmptyMessage(1);
        }
    }

    boolean flag = false;

    @Override
    public void onResume() {
        super.onResume();
        FragmentUtil.currFragTag = Constant.FRAGMENT_FLAG_PROJECT;
        if (!MyApp.iscreate && !MyApp.isupdate && flag) {
            onRefresh();
        }
        flag = true;
        if (MyApp.iscreate) {
            MyApp.iscreate = false;
            onRefresh();
            search_Map("");
        }
        if (MyApp.isupdate) {
            onRefresh();
        }
        if (baidumapstyle != null) baidumapstyle.onResume();

    }

    @Override
    void findView(View view) {
        super.findView();
        if (listview_project == null)
            listview_project = (SwipeRefreshListView) view.findViewById(R.id.listview_project);


        listview_project.setOnRefreshListener(this);
        addDelect();


        /**地图控件**/
        completed = (TextView) view.findViewById(R.id.project_completed);
        ongoing = (TextView) view.findViewById(R.id.project_ongoing);
        if (MyApp.scheduleCountBean != null) {
            textHandler.sendEmptyMessage(0);//设置项目统计数据
        } else {
            ((HomePageActivity) getActivity()).getScheduleCount(textHandler);//获取统计数据
        }
        findViewAndInit_MapButton(view);

    }

    /**
     * 删除方法*
     */
    String stage, stage_type;

    private void addDelect() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                //删除
                SwipeMenuItem deleteItem = new SwipeMenuItem(getActivity());
                deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
                        0x3F, 0x25)));
                deleteItem.setWidth(DensityUtil.dip2px(getActivity(), 90));
                //deleteItem.setIcon(R.mipmap.ic_delete);
                deleteItem.setTitle("删除");
                deleteItem.setTitleSize(20);
                deleteItem.setTitleColor(getActivity().getResources().getColor(R.color.white));
                menu.addMenuItem(deleteItem);
                //下载
                SwipeMenuItem LoadItem = new SwipeMenuItem(getActivity());
                LoadItem.setBackground(R.color.colorfentlan);
                LoadItem.setWidth(DensityUtil.dip2px(getActivity(), 80));
                //deleteItem.setIcon(R.mipmap.ic_delete);
//                LoadItem.setTitle("下载");
                LoadItem.setTitle("同步");
                LoadItem.setTitleSize(20);
                LoadItem.setTitleColor(getActivity().getResources().getColor(R.color.white));
                menu.addMenuItem(LoadItem);
            }
        };

        listview_project.setMenuCreator(creator, new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                MyLog.L(MString.SUCCESSED + " position=" + position + " index=" + index);
                MyApp.currProject.setBean(data.get(position));
                if (index == 0) {
                    //删除方法
                    MyDialog.dialogFordelectPro(getActivity(), data.get(position), position);
                } else {
                    // TODO: 屏蔽项目自动同步操作
//                    if (Cachedata.size() > position
//                            && (Cachedata.get(position).getStage_id().equals(MString.code_null)
//                            || Cachedata.get(position).getStage_id().equals(MString.code_zero))) {
//                        ToastShow.showShort(getActivity(), "此为离线项目！");
//                    } else if (MyApp.isOnLine) {
//                        DataFactory.handler = null;
//                        MyApp.currProject.setBean(data.get(position));
//                        String path = MString.Request + File.separator + MString.Project_
//                                + MString.getValueId(MyApp.currProject.getStage_id(), MyApp.currProject.getUUID());
//                        if (DataFactory.check_cache(getActivity(), path)) {
//                            MyDialog.dialogForupdatePro(getActivity(), MyApp.currProject);//选择是否同步
//                        } else {
//                            MyApp.HTTP.checkStage(handler, 200, SetFileUtil.CheckStageId_type());
//                        }
//                    } else {
//                        ToastShow.showShort(getActivity(), "离线情况下不能下载项目！");
//                    }
                    DataFactory.ProjectClick((BaseActivity) getActivity(), data.get(position));//点击判断函数
                }

            }
        });

        listview_project.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                // Bundle bundle = new Bundle();
                // bundle.putString(MString.PATH, JSON.toJSONString(data.get(i)));
                DataFactory.ProjectItemClick((BaseActivity) getActivity(), data.get(i));//点击判断函数
            }
        });

        addDelExpMaterialHandler();
    }

    String stage_id;

    /**
     * 删除项目方法
     **/
    public void Delect(int position) {
        stage_id = "";
        ProjectItemBean itemBean = data.get(position);
        if (MyApp.isOnLine) {
            if (!itemBean.getStage_id().equals(MString.code_null) && !itemBean.getStage_id().equals(MString.code_zero)) {
                stage_id = itemBean.getStage_id();
                MyApp.HTTP.DelProjectStage(delExpMaterialHandler, HttpStringUtil.SUCCESSED, itemBean.getStage_id());
            } else {
                String path = getActivity().getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Project_ + itemBean.getUUID();
                MyApp.File.delete(new File(path));//删除缓存
                String path2 = getActivity().getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Request + File.separator + MString.Project_ + itemBean.getUUID();
                MyApp.File.delete(new File(path2));//删除同步缓存
                SetFileUtil.delectProjectStageListFile(itemBean);//更新阶段数据
                onRefresh();
                checkDelect();
            }
            mposition = position;
        } else {
            try {
                if (Cachedata.size() > position && (Cachedata.get(position).getStage_id().equals(MString.code_null)
                        || Cachedata.get(position).getStage_id().equals(MString.code_zero))) {
                    String path = getActivity().getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Project_ + Cachedata.get(position).getUUID();
                    String path2 = getActivity().getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Request + File.separator + MString.Project_ + itemBean.getUUID();
                    MyApp.File.delete(new File(path2));//删除同步缓存
                    MyApp.File.delete(new File(path));
                    Cachedata.remove(position);
                    SetFileUtil.setProjectStageListFile(Cachedata);//更新阶段数据
                    SetFileUtil.delectStageMapProjectFile(itemBean);
                    onRefresh();
                    checkDelect();
                } else {
                    ToastShow.showShort(getActivity(), "离线情况下不能删除在线项目！");
                    // Cachedata.get(position).setFlag("del");
                }
            } catch (Exception e) {
            }
        }
    }

    private Handler handler = new Handler() {
        String p = "";

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HttpStringUtil.SUCCESSED:
                    if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                        String path = FastJsonUtil.JsonToZipPathBean((String) msg.obj);
                        if (path.length() > 0) {
                            p = MyApp.File.getCachaPath();
                            MyApp.File.copyFolderPhotos(p + MString.Project_ + SetFileUtil.CheckStageId_type(), MyApp.File.getCachaPath() + MString.Photos);
                            MyApp.HTTP.download(path, p, MString.Project_ + SetFileUtil.CheckStageId_type(), ".zip", handler);
                        }
                    } else {
                        ToastShow.showShort(getActivity(), FastJsonUtil.JsonToCheck_String((String) msg.obj));
                    }
                    break;
                case 1:
                    p = MyApp.File.getCachaPath() + MString.Project_ + SetFileUtil.CheckStageId_type();
                    // MyApp.File.delect(p2);//删除缓存文件夹
                    MyApp.File.delect(p + ".zip");//删除文件夹压缩包
                    DataFactory.setUpdateOn(false);
                    break;
                case 200:
                    if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                        MyApp.HTTP.getload(handler, HttpStringUtil.SUCCESSED, SetFileUtil.CheckStageId());
                    } else {
                        if (!((String) msg.obj).contains("PACK0010")) {
                            MyApp.HTTP.getload(handler, HttpStringUtil.SUCCESSED, SetFileUtil.CheckStageId());
                        } else {
                            ToastShow.showShort(MyApp.activity, FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                    }

                    break;
                case HttpStringUtil.ERROR:
                    ToastShow.showShort(MyApp.activity, "此项目不存在，请手动删除！");
                    break;

            }
        }
    };

    /**
     * 删除方法监听器*
     */
    private void addDelExpMaterialHandler() {
        delExpMaterialHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                        if (s.equals(MString.TRUE)) {
                            //判断有无缓存并删除
                            try {
                                // String path = getActivity().getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Project_ + Cachedata.get(mposition).getUUID();
                                String path2 = getActivity().getFilesDir().getPath() + File.separator + MyApp.openIdent + File.separator + MString.Project_ + stage_id;
                                // MyApp.File.delete(new File(path));
                                MyApp.File.delete(new File(path2));
                                for (ProjectItemBean b : Cachedata) {
                                    if (b.getStage_id().equals(stage_id)) {
                                        Cachedata.remove(b);
                                        break;
                                    }
                                }
                                //  Cachedata.remove(mposition);
                                SetFileUtil.setProjectStageListFile(Cachedata);//更新阶段数据
                            } catch (Exception e) {
                            }
                            for (ProjectItemBean b : data) {
                                if (b.getStage_id().equals(stage_id)) {
                                    data.remove(b);
                                    break;
                                }
                            }
                            //data.remove(mposition);
                            stage_id = "";
                            listview_project.update();
                            checkDelect();
                        } else {
                            ToastShow.showShort(getActivity(), s);
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        break;
                }
            }
        };
    }


    private Handler textHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            completed.setText(MyApp.scheduleCountBean.getCompleted());
            ongoing.setText(MyApp.scheduleCountBean.getOngoing());
        }
    };


    //判断最近项目是否已删除
    private void checkDelect() {
        String id = MString.getValueId(MyApp.currProject.getStage_id(), MyApp.currProject.getUUID());
        ProjectItemBean itemBean = MyApp.File.LoadFileData_ProjectItem(MString.currProject);
        if (itemBean == null) return;
        if (id.equalsIgnoreCase(MString.getValueId(itemBean.getStage_id(), itemBean.getUUID()))) {
            MyApp.currProject.clearBean();
            MyApp.currProject.saveBean();
            String xmlname = MyApp.userInfo.mobilePhone + itemBean.getProject_id() + "fileAccept.xml";
            File file = new File("/data/data/" + getActivity().getPackageName().toString() + "/shared_prefs", xmlname);
            //当调用deleteOnExit()方法时，只是相当于对deleteOnExit（）作一个声明，当程序运行结束，
            // JVM终止时才真正调用deleteOnExit()方法实现删除操作。即该方法是将删除的命令缓存了一下，
            // 到服务停止的时候再进行操作！
            if (file.exists()) file.delete();
        }
    }

    @Override
    void initialization() {
        super.initialization();
        addProjectListHandler();
        addSearchAllProjectHandler();
        Cachedata = GetFileUtil.getProjectStageListFile();//读取缓存
        if (MyApp.isOnLine) {
            onRefresh();//在线刷新
        } else {
            //离线加载
            if (data == null) data = new ArrayList<>();
            data.addAll(getData(startNum, startNum + addNum));
            startNum = startNum + addNum;
            projectListHandler.sendEmptyMessage(1);
        }

        //map
        searchProjectBeanList = GetFileUtil.getMapProjectFile();
        if (MyApp.isOnLine) {
            search_Map("");
        } else {
            if (searchProjectBeanList != null) {
                searchAllProjectHandler.sendEmptyMessage(1);
            }
        }


    }

    /**
     * 设置data数据*
     */
    private List<ProjectItemBean> getData(int start, int index) {
        List<ProjectItemBean> beans = new ArrayList<>();
        if (Cachedata == null || Cachedata.size() == 0) return beans;
        int i = 0;
        for (ProjectItemBean p : Cachedata) {
            if (index <= i) {
                return beans;
            }
            if (i >= start) {

                if (p == null || p.getStage_id() == null || p.getStage_id().equals(MString.code_null))
                    index += 1;
                if (p != null) beans.add(p);
            }
            i++;
        }
        return beans;
    }

    /**
     * 获取所有离线项目
     **/
    private List<ProjectItemBean> getData() {
        List<ProjectItemBean> beans = new ArrayList<>();
        if (Cachedata == null || Cachedata.size() == 0) return beans;
        int i = 0;
        for (ProjectItemBean p : Cachedata) {
            if (p == null || (!StringUtils.isEmpty(p.getStage_id()) && !p.getStage_id().equals(MString.code_zero) && (p.getUUID().equals(MString.code_zero) || StringUtils.isEmpty(p.getUUID())))) {
                beans.add(p);
            }
        }
        return beans;
    }


    List<SearchProjectBean> searchProjectBeanList;

    private void addSearchAllProjectHandler() {
        searchAllProjectHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (searchProjectBeanList == null) {
                                searchProjectBeanList = new ArrayList<>();
                            } else {
                                searchProjectBeanList.clear();

                            }
//                          searchProjectBeanList.addAll(DataFactory.GetProject(FastJsonUtil.JsonToGetSearchAllProject((String) msg.obj), GetFileUtil.getMapProjectFile()));
                            searchProjectBeanList.addAll(FastJsonUtil.JsonToGetSearchAllProject((String) msg.obj));
                            SetFileUtil.setMapProjectFile(searchProjectBeanList); //存储
                            if (searchProjectBeanList != null) {
                                //MyApp.File.SaveFileData(MString.File_ProjectMap, "{\"projectList\":" + JSON.toJSONString(searchProjectBeanList) + "}");//存储
                                searchAllProjectHandler.sendEmptyMessage(1);
                            }
                        } else {
                            String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                            ToastShow.showShort(getActivity(), s);
                        }
                        break;
                    case 1://加载地图数据
                        mBaiduMap.clear();
                        boolean statu = true;
                        for (SearchProjectBean p : searchProjectBeanList) {
                            if (p == null) return;
                            if (p.getLat() == null || p.getLng() == null) return;
                            if (p.getLat().length() == 0 || p.getLng().length() == 0) return;
                            int image = 0;
                            //1为完成 0为未完成
                            if (p.getIs_finish().equals(MString.code_one)) {
                                image = R.mipmap.project_finish;
                            } else {
                                image = R.mipmap.project_notfinish;
                            }
                            baidumapstyle.addMarka(getActivity(), p, image);
                            if (statu) {
                                statu = false;
                                LatLng point = new LatLng(Double.parseDouble(p.getLat()), Double.parseDouble(p.getLng()));
                                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().target(point).zoom(MyApp.zoom).build()));
                                mBaiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(point));//将位置设为中心点
                            }
                        }
                        //baidumapstyle.setMCLICK(getActivity());
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(getActivity(), (String) msg.obj);
                        break;
                }
            }
        };
    }

    private void addProjectListHandler() {
        projectListHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case HttpStringUtil.SUCCESSED:
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = new ArrayList<>();
                            } else {
                                data.clear();
                            }
                            // addHeadReceive();
                            if (data == null) return;
                            /**过滤**/
                            if (data != null) {
                                if (project_name.length() > 0 || start_year.length() > 0 ||
                                        end_year.length() > 0 ||
                                        current_stage.length() > 0 ||
                                        project_type.length() > 0 ||
                                        current_schedule.length() > 0 ||
                                        owner_unit.length() > 0 ||
                                        design_unit.length() > 0 ||
                                        owner_unit_string.length() > 0 ||
                                        design_unit_string.length() > 0) {
                                    data.addAll(FastJsonUtil.JsonToGetProjectListBean((String) msg.obj));

                                } else {
                                    data.addAll(DataFactory.GetNewProject(FastJsonUtil.JsonToGetProjectListBean((String) msg.obj), GetFileUtil.getProjectStageListOffLineFile()));
//                                    data.addAll(DataFactory.GetNewProject(FastJsonUtil.JsonToGetProjectListBean((String) msg.obj), getData()));
//                                    data.addAll(FastJsonUtil.JsonToGetProjectListBean((String) msg.obj));
                                    SetFileUtil.updateProjectStageListFile(data);//更新
                                }
                            } else {
                                SetFileUtil.updateProjectStageListFile(data);//更新
                            }

                            projectListHandler.sendEmptyMessage(1);
                            startNum = startNum + addNum;
                            MyLog.L(MString.SUCCESSED + JSON.toJSONString(data));
                        } else {
                            listview_project.setRefreshing(false);
                            String s = FastJsonUtil.JsonToCheck_String((String) msg.obj);
                            ToastShow.showShort(getActivity(), s);
                        }
                        break;
                    case 1://加载listview数据
                        if (data == null) MyApp.currProject.saveNullBean();
                        if (adapter == null) {
                            if (data == null) data = new ArrayList<>();
                            adapter = new ProjectAdapter(getActivity(), data);
                            listview_project.setAdapter(adapter);
                            listview_project.setFragment(baseFragment);
                            listview_project.setCanScroll(true);
                            listview_project.setDivider(6);
                            listview_project.setRefreshing(false);
                        } else {
                            listview_project.update();
                            listview_project.setRefreshing(false);
                            listview_project.removeFooterView();
                        }
                        break;
                    case HttpStringUtil.ADDMROE:
                        int num = 0;
                        if (FastJsonUtil.JsonToCheck((String) msg.obj)) {
                            if (data == null) {
                                data = FastJsonUtil.JsonToGetProjectListBean((String) msg.obj);
                            }
                            num = Integer.parseInt(data.size() + "");
                            if (data == null) return;
                            /**过滤**/
                            data.addAll(FastJsonUtil.JsonToGetProjectListBean((String) msg.obj));
                            SetFileUtil.updateProjectStageListFile(data);//更新
                            projectListHandler.sendEmptyMessage(1);
                            if (num < data.size()) {
                                startNum = startNum + addNum;
                            } else {
                                ToastShow.showShort(getActivity(), "没有数据了");
                            }
                        } else {
                            listview_project.setRefreshing(false);
                            ToastShow.showShort(getActivity(), FastJsonUtil.JsonToCheck_String((String) msg.obj));
                        }
                        break;
                    case HttpStringUtil.ERROR:
                        ToastShow.showShort(getActivity(), (String) msg.obj);
                        projectListHandler.sendEmptyMessage(1);
                        break;

                }
            }
        };
    }


    private void addHeadReceive() {
//        String revicejson = MyApp.File.ReadFileData(MString.ProjectStageReviceListFile);
//        MyLog.L(MString.SUCCESSED + " revicejson==" + revicejson);
//        if (revicejson != null && revicejson.length() > 0) {
//            try {
//                data.addAll(FastJsonUtil.JsonToGetProjectListBean(revicejson));
//            } catch (Exception e) {
//            }
//        }
    }
    /**
     * ********************************地图控件操作******************************************************
     */
    /**
     * 设置地图*
     */
    public MapView mMapView;
    public BaiduMap mBaiduMap;
    public MBaiduMap baidumapstyle;

    //public static LatLng currentPt;//选定的点位
    private void findViewAndInit_MapButton(View view) {
        map_item = (RelativeLayout) view.findViewById(R.id.map_item);
        statistics = (LinearLayout) view.findViewById(R.id.statistics);
        TextView projectmap_display = (TextView) view.findViewById(R.id.projectmap_display);
        projectmap_display.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                disPlay(v);
            }
        });
        baidumapstyle = (MBaiduMap) view.findViewById(R.id.baidumapstyle);
        mMapView = baidumapstyle.getMapView();
        mBaiduMap = baidumapstyle.getBaiduMap();
        //baidumapstyle.setMarka(currentPt);
        baidumapstyle.hidePosition();
    }

    /**
     * 显示与隐藏按钮*
     */
    public void disPlay(View view) {
        if (statistics.getVisibility() == View.VISIBLE) {
            statistics.setVisibility(View.GONE);
            view.setBackgroundResource(R.mipmap.fold);
        } else {
            statistics.setVisibility(View.VISIBLE);
            view.setBackgroundResource(R.mipmap.unfold);
        }
    }

    int startNum = 0;
    int addNum = MyApp.addNum;

    public String project_name = "", start_year = "", end_year = "", current_stage = "", project_type = "", current_schedule = "", owner_unit = "", design_unit = "", owner_unit_string = "", design_unit_string = "";
    TextView search_text;

    public Handler refreshhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            onRefresh();
        }
    };

    @Override
    public void onRefresh() {
        if (getActivity() != null) getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    startNum = 0;
                    addNum = MyApp.addNum;
                    if (Cachedata == null) {
                        Cachedata = GetFileUtil.getProjectStageListFile();//读取缓存
                    } else {
                        Cachedata.clear();
                        Cachedata.addAll(GetFileUtil.getProjectStageListFile());
                    }
                    if (MyApp.isOnLine) {
                        if (project_name.length() != 0 || start_year.length() != 0 || end_year.length() != 0 || current_stage.length() != 0 || project_type.length() != 0 || current_schedule.length() != 0 || design_unit.length() != 0 || owner_unit.length() != 0) {
                            search(HttpStringUtil.SUCCESSED);
                            if (search_text == null)
                                search_text = (TextView) getActivity().findViewById(R.id.search_text);
                            search_text.setText(project_name);
                        } else {
                            if (search_text == null)
                                search_text = (TextView) getActivity().findViewById(R.id.search_text);

                            search_text.setText("");
                            MyApp.HTTP.getProjectList(projectListHandler, HttpStringUtil.SUCCESSED, "", startNum, startNum + addNum);
                        }
                    } else {

                        if (data == null) data = new ArrayList<>();
                        data.clear();
                        //离线加载
                        if (project_name.length() != 0 || start_year.length() != 0 || end_year.length() != 0 || current_stage.length() != 0 || project_type.length() != 0 || current_schedule.length() != 0 || design_unit.length() != 0 || owner_unit.length() != 0) {

                            if (search_text == null)
                                search_text = (TextView) getActivity().findViewById(R.id.search_text);
                            search_text.setText(project_name);
                            int i = 0;
                            for (ProjectItemBean p : Cachedata) {
                                if (i <= addNum) {
                                    if (checkSearch(p)) {
                                        data.add(p);
                                        i++;
                                    }
                                } else {
                                    break;
                                }

                            }
                        } else {
                            if (search_text == null)
                                search_text = (TextView) getActivity().findViewById(R.id.search_text);

                            search_text.setText("");
                            data.addAll(getData(startNum, startNum + addNum));
                        }
                        startNum = startNum + addNum;
                        projectListHandler.sendEmptyMessage(1);

                    }


                } catch (Exception e) {
                    MyLog.L(e.getMessage());
                }
            }
        });

    }


    private boolean checkSearch(ProjectItemBean p) {
        boolean flag = true;
        if (project_name.length() != 0 && !p.getProject_name().contains(project_name)) {
            flag = false;
        }
        if ((start_year.length() != 0 && end_year.length() != 0)) {
            int year = TimeUtil.getYear(p.getCreate_time());
            if (Integer.parseInt(start_year) < year && year < Integer.parseInt(end_year)) {

            } else {
                flag = false;
            }
        }
        if (current_stage.length() != 0 && !p.getStage().equals(current_stage)) {


            flag = false;
        }
        if (project_type.length() != 0 && !p.getProject_type().equals(project_type)) {


            flag = false;
        }
        if (current_schedule.length() != 0 && !p.getCurrent_schedule().equals(current_schedule)) {
            flag = false;
        }

        MyLog.L(MString.SUCCESSED + " current_schedule=" + current_schedule + " current_stage=" + current_stage);
        MyLog.L(MString.SUCCESSED + " p.getStage()=" + p.getStage() + " p.getCurrent_schedule()=" + p.getCurrent_schedule());
        return flag;
        //if (design_unit.length() != 0 && p.getManager().contains(design_unit)) flag = true;
        //if (owner_unit.length() != 0 && p.getExplorationer().contains(owner_unit)) flag = true;

    }

    @Override
    public void Refresh() {
        super.Refresh();
        MyLog.L(MString.SUCCESSED + "刷新2");
        if (MyApp.scheduleCountBean != null) {
            textHandler.sendEmptyMessage(0);
        }
    }

    @Override
    public void addMore() {
        super.addMore();
        if (MyApp.isOnLine) {
            if (project_name.length() != 0 || start_year.length() != 0 || end_year.length() != 0 || current_stage.length() != 0 || project_type.length() != 0 || current_schedule.length() != 0 || design_unit.length() != 0 || owner_unit.length() != 0) {
                search(HttpStringUtil.ADDMROE);
            } else {
                MyApp.HTTP.getProjectList(projectListHandler, HttpStringUtil.ADDMROE, "", startNum, startNum + addNum);
            }
        } else {
            //离线加载
            if (data == null) data = new ArrayList<>();
            int num = data.size();
            //离线加载
            if (project_name.length() != 0 || start_year.length() != 0 || end_year.length() != 0 || current_stage.length() != 0 || project_type.length() != 0 || current_schedule.length() != 0 || design_unit.length() != 0 || owner_unit.length() != 0) {
                int i = 0;
                for (ProjectItemBean p : Cachedata) {
                    if (i <= (startNum + addNum)) {
                        if (checkSearch(p)) {
                            data.add(p);
                            i++;
                        }
                    } else {
                        break;
                    }
                }
            } else {
                data.addAll(getData(startNum, startNum + addNum));
            }
            projectListHandler.sendEmptyMessage(1);
            if (num < data.size()) {
                startNum = startNum + addNum;
            } else {
                ToastShow.showShort(getActivity(), "没有数据了");
            }


        }

    }

    private void search(int code) {
        MyApp.HTTP.getSearchProject(projectListHandler, code, project_name, start_year, end_year, current_stage, project_type, current_schedule, owner_unit, design_unit, startNum, startNum + addNum);
    }

    @Override
    public void onDestroy() {
        data.clear();
        listview_project.destory(listview_project);
        if (baidumapstyle != null) baidumapstyle.onDestroy();
        super.onDestroy();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (baidumapstyle != null) baidumapstyle.onPause();
    }
}
